import "./App.css";
import { useState } from "react";

const App = () => {
  const [counter, setCounter] = useState(1);
  const [user, setUser] = useState({ name: "孙悟空", age: 18 });

  const addHandler = () => {
    // setCounter(counter + 1); // 将counter值修改为2
    setTimeout(() => {
      setCounter((prevCounter) => {
        /*
         *   setState()中回调函数的返回值将会成为新的state值
         *       回调函数执行时，React会将最新的state值作为参数传递
         * */
        return prevCounter + 1;
      });
    }, 1000);
  };
  const updateUserHandler = () => {
    // setUser({name:'猪八戒'});

    // 如果直接修改旧的state对象，由于对象还是那个对象，所以不会生效
    // user.name = '猪八戒';
    // console.log(user);
    // setUser(user);

    // const newUser = Object.assign({}, user);
    // newUser.name = '猪八戒';
    // setUser(newUser);
    setUser({ ...user, name: "猪八戒" });
  };
  return (
    <div className={"app"}>
      <h1>
        {counter}--{user.name}--{user.age}
      </h1>
      <button onClick={addHandler}>+1</button>
      <button onClick={updateUserHandler}>点我</button>
    </div>
  );
};

export default App;
